<script setup>
import { ElMessage } from "element-plus";
import { reactive, onDeactivated, onActivated, ref, computed } from "vue";
import { robotInspectionLog } from "@/api/inspection/environment-monitor";
import { thresholdConfig } from "@/api/inspection/environment-monitor";
import { useRoute } from "vue-router";

// import ch4 from "@/assets/images/inspection/icon_ch4.png";
// import co from "@/assets/images/inspection/icon_co.png";
import dust from "@/assets/images/inspection/icon_dust.png";
import fire from "@/assets/images/inspection/icon_fire.png";
// import h2s from "@/assets/images/inspection/icon_h2s.png";
import humidity from "@/assets/images/inspection/icon_humidity.png";
import noise from "@/assets/images/inspection/icon_noise.png";
import particles from "@/assets/images/inspection/icon_particles.png";
import smoke from "@/assets/images/inspection/icon_smoke.png";
import temper from "@/assets/images/inspection/icon_temper.png";
import { robotTypes } from "./utils/index.js";

// 机器人code
const route = useRoute();
const code = route.query.id;

// 环境监测数据
const enviromentData = ref({});
// 定时器
let timer;
/**
 * @description: 获取环境监测数据
 * @return {*}
 */
async function getData() {
  clearTimeout(timer);
  const { data } = await robotInspectionLog(code);
  enviromentData.value = data || {};
  timer = setTimeout(() => getData(), 5000);
}

// 环境监测数据
const enviromentList = computed(() => {
  const { rType } = route.query;
  if (rType === robotTypes.OUTSIDE) {
    return [
      {
        id: "temperature",
        value: enviromentData.value.temperature,
        name: "温度",
        unit: "°C",
        img: temper,
      },
      {
        id: "humidity",
        value: enviromentData.value.humidity,
        name: "湿度",
        unit: "%",
        img: humidity,
      },
      {
        id: "pmTF",
        value: enviromentData.value.pm,
        name: "PM2.5",
        unit: "ug/m³",
        img: particles,
      },
      {
        id: "pmTen",
        value: enviromentData.value.pm10,
        name: "PM10",
        unit: "ug/m³",
        img: dust,
      },
      {
        id: "noise",
        value: enviromentData.value.noise,
        name: "噪音",
        unit: "DB",
        img: noise,
      },
      {
        id: "fireMax",
        value: enviromentData.value.fireMax,
        name: "热像仪最高温",
        unit: "°C",
        img: temper,
      },
    ];
  } else if (rType === robotTypes.INSIDE) {
    return [
      {
        id: "temperature",
        value: enviromentData.value.temperature,
        name: "温度",
        unit: "°C",
        img: temper,
      },
      {
        id: "humidity",
        value: enviromentData.value.humidity,
        name: "湿度",
        unit: "%",
        img: humidity,
      },
      {
        id: "pmTF",
        value: enviromentData.value.pm,
        name: "PM2.5",
        unit: "ug/m³",
        img: particles,
      },
      {
        id: "pmTen",
        value: enviromentData.value.pm10,
        name: "PM10",
        unit: "ug/m³",
        img: dust,
      },
      {
        id: "noise",
        value: enviromentData.value.noise,
        name: "噪音",
        unit: "DB",
        img: noise,
      },
      {
        id: "fireMax",
        value: enviromentData.value.blaze,
        name: "火焰强度",
        unit: "%",
        img: fire,
      },
      {
        id: "smoke",
        value: enviromentData.value.smoke,
        name: "烟雾状态",
        unit: "",
        img: smoke,
      },
      {
        id: "light",
        value: enviromentData.value.light,
        name: "光照强度",
        unit: "%",
        img: temper,
      },
    ];
  } else {
    return [];
  }
});

const isOutside = computed(() => {
  const { rType } = route.query;
  return rType === robotTypes.OUTSIDE;
});

function hasData(value) {
  return value || value === 0;
}

// 阈值数据
const threshold = reactive({
  params: { id: null, edit: false },
  temperature: { value: "" },
  humidity: { value: "" },
  pmTF: { value: "" },
  pmTen: { value: "" },
  noise: { value: "" },
  fireMax: { value: "" },
});

// 打开弹窗时获取阈值
async function getThreshold(id) {
  const { data } = await thresholdConfig.read({
    type: "environment-threshold",
    code,
  });
  threshold.params = { id: null, edit: false };
  data.list.find((item) => {
    if (item.key.indexOf(id) != -1) {
      threshold[id].value = item.value;
      threshold.params = { id: item.id, edit: true };
    }
  });
}

// 设置阈值
async function setThreshold(id) {
  if (threshold.params.edit) {
    // 更新阈值
    const { message } = await thresholdConfig.update({
      id: threshold.params.id,
      key: `outsideInspection-${id}-${code}`,
      value: threshold[id].value,
      cacheType: "redis",
      effectiveTime: 0,
      type: "environment_threshold",
      code,
    });
    ElMessage({ type: "success", message });
  } else {
    // 创建阈值
    const { message } = await thresholdConfig.create({
      key: `outsideInspection-${id}-${code}`,
      value: threshold[id].value,
      cacheType: "redis",
      effectiveTime: 0,
      type: "environment_threshold",
      code,
    });
    ElMessage({ type: "success", message });
  }
}

onActivated(() => {
  getData();
});

onDeactivated(() => {
  clearTimeout(timer);
});
</script>

<template>
  <div class="w-full h-full content-start grid grid-cols-2 gap-4 grid-rows-5">
    <div
      v-for="item in enviromentList"
      :key="item.id"
      class="cursor-pointer h-full flex flex-col items-center justify-center bg-[#26323f] select-none px-4 rounded"
    >
      <div class="w-full flex justify-between items-center mb-2 text-[#24A0FF]">
        <span class="text-3xl whitespace-nowrap overflow-hidden text-ellipsis">
          {{ hasData(item.value) ? `${item.value}${item.unit}` : "无数据" }}
        </span>
        <div v-if="isOutside" class="min-w-[188px]">
          <el-popover placement="bottom" :width="240" trigger="click">
            <div class="flex justify-between items-center">
              <el-input v-model="threshold[item.id].value" class="mr-3" />
              <el-button type="primary" @click="setThreshold(item.id)">
                确认
              </el-button>
            </div>

            <template #reference>
              <el-button type="primary" @click="getThreshold(item.id)">
                设置阈值
              </el-button>
            </template>
          </el-popover>
          <el-button type="danger"> 取消报警 </el-button>
        </div>
      </div>
      <div class="w-full flex items-center justify-items-start text-lg">
        <img :src="item.img" />
        <span class="ml-4 whitespace-nowrap overflow-hidden text-ellipsis">
          {{ item.name }}
        </span>
      </div>
    </div>
  </div>
</template>
